﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using PlacementManager;

public partial class Home_Venue2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            this.txtSearchName.Focus();
        }
    }
    /// <summary>
    /// This method filters Linq datasource for only current placements for current placements grid view.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ldsCurrentPlacements_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from pt in db.PlacementTypes
                    join vpt in db.VenuePlacementTypes on pt.PlacementTypeId equals vpt.PlacementTypeId
                    where vpt.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                        && pt.DateStart < DateTime.Now && pt.DateEnd >= DateTime.Now
                    && pt.IsActive == true
                    orderby pt.Unit.UnitCode
                    select new
                    {
                        Year = pt.Year,
                        PlacementTypeName = pt.PlacementTypeName,
                        PlacementTypeId = pt.PlacementTypeId,
                        CampusCode = pt.Campus.CampusCode,
                        CategoryName = pt.Category.CategoryName,
                        UnitCode = pt.Unit.UnitCode,
                        SemesterId = pt.SemesterId,
                        UnitId = pt.UnitId,
                        CategoryId = pt.CategoryId,
                        AttendancePatternId = pt.AttendancePatternId,
                        CampusId = pt.CampusId,
                        RequiredHours = pt.RequiredHours,
                        IsActive = pt.IsActive,
                        DateStart = pt.DateStart,
                        DateEnd = pt.DateEnd,
                        DateCreated = pt.DateCreated,
                        CreatedBy = pt.CreatedBy,
                        DateUpdated = pt.DateUpdated,
                        UpdatedBy = pt.UpdatedBy,
                        Allocations = pt.Allocations.Count
                    };
        e.Result = query;
    }

    protected void ldsVenues_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from v in db.Venues
                    where v.VenueName.StartsWith(this.txtSearchName.Text)
                    orderby v.VenueName
                    select new
                    {
                        VenueId = v.VenueId,
                        VenueName = v.VenueName.Substring(0, 45)
                    };
        e.Result = query;
    }
    protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        this.gvVenues.DataBind();
    }

    protected void BindCurrentPlacements()
    {
        this.gvCurrentPlacements.DataBind();
    }

    protected void BindPastPlacements()
    {
        this.gvPastPlacements.DataBind();
    }

    protected void BindFuturePlacements()
    {
        this.gvFuturePlacements.DataBind();
    }
    protected void BindVenueDetail()
    {
        this.fvVenueDetail.DataBind();
        this.lvVenueAddresses.DataBind();
        this.lvVenueCategories.DataBind();
        this.lvVenueUnits.DataBind();
    }
    protected void BindVenueContacts()
    {
        this.lvVenueContacts.DataBind();
    }
    protected void BindVenueNotes()
    {
        this.gvNotes.DataBind();
    }
    protected void gvVenues_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.BindVenueDetail();
        this.BindVenueContacts();
        this.BindVenueNotes();
        this.BindCurrentPlacements();
        this.BindPastPlacements();
        this.BindFuturePlacements();
    }

    protected void fvVenueDetail_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
        this.gvVenues.DataBind();
    }

    protected void ldsVenueContacts_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from c in db.Contacts
                    join vc in db.VenueContacts on c.ContactId equals vc.ContactId
                    where vc.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())

                    select c;
        e.Result = query;
    }

    protected void ldsAddress_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {

    }
    protected void gvVenueContacts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            FormView fvAddress = (FormView)e.Row.FindControl("fvAddress");
            if (fvAddress != null)
            {
                int contactId = Int32.Parse(DataBinder.Eval(e.Row.DataItem, "ContactId").ToString());

                PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

                var address = from a in db.Addresses
                              join ca in db.ContactAddresses on a.AddressId equals ca.AddressId
                              where ca.ContactId == contactId
                              select new
                              {
                                  AddressId = a.AddressId,
                                  Address1 = a.Address1,
                                  Address2 = a.Address2,
                                  Street = a.Street,
                                  City = a.City,
                                  PostCode = a.PostCode,
                                  StateId = a.StateId,
                                  CountryId = a.CountryId,
                                  IsPostal = a.IsPostal,
                                  Latitude = a.Latitude,
                                  Longitude = a.Longitude,
                                  IsActive = a.IsActive,
                                  DateCreated = a.DateCreated,
                                  CreatedBy = a.CreatedBy,
                                  DateUpdated = a.DateUpdated,
                                  UpdatedBy = a.UpdatedBy
                              }
                            ;
                fvAddress.DataSource = address;
                fvAddress.DataBind();
            }
        }

    }
    protected void ldsVenueAddresses_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from a in db.Addresses
                    join va in db.VenueAddresses on a.AddressId equals va.AddressId
                    where va.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                    && va.IsActive == true
                    && a.IsActive == true
                    orderby va.IsPrimary
                    select a;

        e.Result = query;
    }

    /// <summary>
    /// This method is used for attaching datasource to the nested grid view "gvAllocatedStudents" 
    /// present in the cell "Allocated".Here PlacementTypeId is stored in a hidden field, which is then used
    /// in the datasource.
    /// </summary> 
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvCurrentPlacements_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow gvr = e.Row;
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            GridView gvAllocatedStudents = (GridView)gvr.FindControl("gvAllocatedStudents");

            if (gvAllocatedStudents != null)
            {
                HiddenField hfPlacementTypeId = (HiddenField)gvr.FindControl("hfPlacementTypeId");

                PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
                var query = from u in db.Users
                            join a in db.Allocations on u.UserId equals a.UserId
                            where a.PlacementTypeId == Int32.Parse(hfPlacementTypeId.Value)
                            orderby u.LastName
                            select new
                            {
                                LastName = u.LastName,
                                FirstName = u.FirstName,
                                IdNumber = u.IdNumber
                            };

                gvAllocatedStudents.DataSource = query;
                gvAllocatedStudents.DataBind();
            }
        }
    }

    /// <summary>
    /// This method is used for attaching datasource to the nested grid view "gvPastAllocatedStudents" 
    /// present in the cell "Allocated".Here PlacementTypeId is stored in a hidden field, which is then used
    /// in the datasource for the nested grid.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvPastPlacements_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow gvr = e.Row;
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            GridView gvPastAllocatedStudents = (GridView)gvr.FindControl("gvPastAllocatedStudents");

            if (gvPastAllocatedStudents != null)
            {
                HiddenField hfPlacementTypeId = (HiddenField)gvr.FindControl("hfPlacementTypeId0");

                PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
                var query = from u in db.Users
                            join a in db.Allocations on u.UserId equals a.UserId
                            where a.PlacementTypeId == Int32.Parse(hfPlacementTypeId.Value)
                            orderby u.LastName
                            select new
                            {
                                LastName = u.LastName,
                                FirstName = u.FirstName,
                                IdNumber = u.IdNumber
                            };

                gvPastAllocatedStudents.DataSource = query;
                gvPastAllocatedStudents.DataBind();
            }
        }
    }

    /// This method is used for attaching datasource to the nested grid view "gvFutureAllocatedStudents" 
    /// present in the cell "Allocated".Here PlacementTypeId is stored in a hidden field, which is then used
    /// in the datasource for the nested grid.
    protected void gvFuturePlacements_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow gvr = e.Row;
        if (gvr.RowType == DataControlRowType.DataRow)
        {
            GridView gvFutureAllocatedStudents = (GridView)gvr.FindControl("gvFutureAllocatedStudents");

            if (gvFutureAllocatedStudents != null)
            {
                HiddenField hfFuturePlacementTypeId = (HiddenField)gvr.FindControl("hfFuturePlacementTypeId");

                PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
                var query = from u in db.Users
                            join a in db.Allocations on u.UserId equals a.UserId
                            where a.PlacementTypeId == Int32.Parse(hfFuturePlacementTypeId.Value)
                            orderby u.LastName
                            select new
                            {
                                LastName = u.LastName,
                                FirstName = u.FirstName,
                                IdNumber = u.IdNumber
                            };

                gvFutureAllocatedStudents.DataSource = query;
                gvFutureAllocatedStudents.DataBind();
            }
        }
    }

    /// <summary>
    /// This method filters Linq datasource for only past placements for past placements grid view.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ldsPastPlacements_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from pt in db.PlacementTypes
                    join vpt in db.VenuePlacementTypes on pt.PlacementTypeId equals vpt.PlacementTypeId
                    where vpt.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                        && pt.DateStart < DateTime.Now && pt.DateEnd < DateTime.Now
                    && pt.IsActive == true
                    orderby pt.Unit.UnitCode
                    select new
                    {
                        Year = pt.Year,
                        PlacementTypeName = pt.PlacementTypeName,
                        PlacementTypeId = pt.PlacementTypeId,
                        CampusCode = pt.Campus.CampusCode,
                        CategoryName = pt.Category.CategoryName,
                        UnitCode = pt.Unit.UnitCode,
                        SemesterId = pt.SemesterId,
                        UnitId = pt.UnitId,
                        CategoryId = pt.CategoryId,
                        AttendancePatternId = pt.AttendancePatternId,
                        CampusId = pt.CampusId,
                        RequiredHours = pt.RequiredHours,
                        IsActive = pt.IsActive,
                        DateStart = pt.DateStart,
                        DateEnd = pt.DateEnd,
                        DateCreated = pt.DateCreated,
                        CreatedBy = pt.CreatedBy,
                        DateUpdated = pt.DateUpdated,
                        UpdatedBy = pt.UpdatedBy,
                        Allocations = pt.Allocations.Count
                    };
        e.Result = query;

    }

    /// <summary>
    /// This method filters Linq datasource for only future placements for future placements grid view.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ldsFuturePlacements_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from pt in db.PlacementTypes
                    join vpt in db.VenuePlacementTypes on pt.PlacementTypeId equals vpt.PlacementTypeId
                    where vpt.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                        && pt.DateStart > DateTime.Now && pt.DateEnd > DateTime.Now
                    && pt.IsActive == true
                    orderby pt.Unit.UnitCode
                    select new
                    {
                        Year = pt.Year,
                        PlacementTypeName = pt.PlacementTypeName,
                        PlacementTypeId = pt.PlacementTypeId,
                        CampusCode = pt.Campus.CampusCode,
                        CategoryName = pt.Category.CategoryName,
                        UnitCode = pt.Unit.UnitCode,
                        SemesterId = pt.SemesterId,
                        UnitId = pt.UnitId,
                        CategoryId = pt.CategoryId,
                        AttendancePatternId = pt.AttendancePatternId,
                        CampusId = pt.CampusId,
                        RequiredHours = pt.RequiredHours,
                        IsActive = pt.IsActive,
                        DateStart = pt.DateStart,
                        DateEnd = pt.DateEnd,
                        DateCreated = pt.DateCreated,
                        CreatedBy = pt.CreatedBy,
                        DateUpdated = pt.DateUpdated,
                        UpdatedBy = pt.UpdatedBy,
                        Allocations = pt.Allocations.Count
                    };
        e.Result = query;
    }

    /// <summary>
    /// This method fills in the missing values for inserting new venue.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void fvVenueDetail_ItemInserting(object sender, FormViewInsertEventArgs e)
    {
        //Check if venue already exists!
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
        TextBox venueName = ((TextBox)fvVenueDetail.FindControl("VenueNameTextBox"));
        List<Venue> venues = (from v in db.Venues
                              where v.VenueName == venueName.Text
                              && v.IsActive == true
                              select v).ToList<Venue>();

        if (venues.Count > 0)
        {
            CustomValidator cv = (CustomValidator)this.Find(fvVenueDetail, "DuplicateVenueValidator");
            cv.IsValid = false;
            e.Cancel = true;
            return;
        }

        //Add rest of the values
        string user = User.Identity.Name;
        e.Values.Add("isActive", true);
        e.Values.Add("DateCreated", DateTime.Now);
        e.Values.Add("CreatedBy", user);
        e.Values.Add("DateUpdated", DateTime.Now);
        e.Values.Add("UpdatedBy", user);

    }
    private void SetRowValueValueByKey(GridView GridView, string DataKeyValue)
    {
        GridView.DataBind();
        int intSelectedIndex = 0;
        int intPageIndex = 0;
        int intGridViewPages = GridView.PageCount;

        // Loop thru each page in the GridView
        for (int intPage = 0; intPage < intGridViewPages; intPage++)
        {
            // Set the current GridView page
            GridView.PageIndex = intPage;
            // Bind the GridView to the current page
            GridView.DataBind();

            for (int i = 0; i < GridView.Rows.Count; i++)
            {
                Label ctr = (Label)(GridView.Rows[i].Cells[1].FindControl("lblVenueName"));
                if (ctr.Text == DataKeyValue)
                {
                    // If it is a match set the variables and exit
                    intSelectedIndex = i;
                    intPageIndex = intPage;
                    break;
                }
            }
        }

        // Set the GridView to the values found
        GridView.PageIndex = intPageIndex;
        GridView.SelectedIndex = intSelectedIndex;

    }
    protected void fvVenueDetail_ItemInserted1(object sender, FormViewInsertedEventArgs e)
    {
        txtSearchName.Text = e.Values["VenueName"].ToString();
        gvVenues.DataBind();
        gvVenues.SelectedIndex = 0;
        updtpnlVenuesGrid.Update();

        //List veiw Venue Addresses
        lvVenueAddresses.DataBind();
        lvVenueCategories.DataBind();
        updtpnlVenueContacts.Update();
        //To Do:- Figure out the problem and fix it
        ((ListView)this.Find(this, "lvVenueUnits")).DataBind();

    }
    protected void fvVenueDetail_ModeChanged(object sender, EventArgs e)
    {
        gvVenues.DataBind();
    }
    protected void fvVenueDetail_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        string user = Request.ServerVariables["AUTH_USER"].ToString();
        e.NewValues.Remove("DateUpdated");
        e.NewValues.Remove("UpdatedBy");
        e.NewValues.Add("DateUpdated", DateTime.Now);
        e.NewValues.Add("UpdatedBy", user);
    }
    protected void lvVenueAddresses_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        string user = User.Identity.Name;

        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        Address a = new Address();
        a.Address1 = e.Values["Address1"].ToString();
        a.Address2 = e.Values["Address2"].ToString();
        a.City = e.Values["City"].ToString();
        DropDownList countryDropDown = (DropDownList)this.Find(this.lvVenueAddresses, "Country");
        a.CountryId = Int32.Parse(countryDropDown.SelectedValue.ToString());
        a.CreatedBy = user;
        a.DateCreated = DateTime.Now;
        a.DateUpdated = DateTime.Now;
        a.IsActive = true;
        a.IsPostal = true;
        a.Latitude = 0;
        a.Longitude = 0;
        a.PostCode = e.Values["PostCode"].ToString();
        //ToDo: StateId

        DropDownList stateDropDown = (DropDownList)this.Find(this.lvVenueAddresses, "State");
        a.StateId = Int32.Parse(stateDropDown.SelectedValue.ToString());

        a.Street = e.Values["Street"].ToString();

        a.UpdatedBy = user;

        VenueAddress va = new VenueAddress();
        va.CreatedBy = user;
        va.DateCreated = DateTime.Now;
        va.DateUpdated = DateTime.Now;
        va.IsActive = true;
        va.IsPrimary = true;
        va.UpdatedBy = user;
        va.VenueId = (int)gvVenues.SelectedDataKey.Value;

        a.VenueAddresses.Add(va);

        db.Addresses.InsertOnSubmit(a);
        db.SubmitChanges();

        int newAddressId = a.AddressId;
        e.Cancel = true;

        lvVenueAddresses.DataBind();

    }

    /// <summary>
    /// This method is written as the child control could not be found using findcontrol.
    /// Might be a bug.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    private Control Find(Control control, string id)
    {
        if (control.ID == id)
        {
            return control;
        }
        foreach (Control child in control.Controls)
        {
            Control result = this.Find(child, id);
            if (result != null)
            {
                return result;
            }
        }
        return null;
    }
    protected void lvVenueAddresses_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        string user = User.Identity.Name;
        e.NewValues.Remove("DateUpdated");
        e.NewValues.Remove("UpdatedBy");
        e.NewValues.Add("DateUpdated", DateTime.Now);
        e.NewValues.Add("UpdatedBy", user);
    }
    protected void ldsVenueCategories_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from va in db.VenueCategories
                    join c in db.Categories on va.CategoryId equals c.CategoryId
                    where va.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                    && va.IsActive == true
                    && c.IsActive == true
                    orderby c.CategoryName
                    select va;

        e.Result = query;
    }
    protected void lvVenueCatagories_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        //Check for duplication first
        DropDownList CategoryNameDropDown = (DropDownList)this.Find(((ListView)sender), "CategoryNameDropDown");

        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        List<VenueCategory> venueCategories = (from vc in db.VenueCategories
                                               where vc.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                                               && vc.IsActive == true
                                               && vc.CategoryId == Int32.Parse(CategoryNameDropDown.SelectedValue.ToString())
                                               select vc).ToList<VenueCategory>();

        if (venueCategories.Count > 0)
        {
            CustomValidator cv = (CustomValidator)this.Find(((ListView)sender), "DuplicateCategoryValidator");
            cv.IsValid = false;
            e.Cancel = true;
            return;
        }

        //Add Rest of the values
        string user = User.Identity.Name;
        e.Values.Add("isActive", true);
        e.Values.Add("DateCreated", DateTime.Now);
        e.Values.Add("CreatedBy", user);
        e.Values.Add("DateUpdated", DateTime.Now);
        e.Values.Add("UpdatedBy", user);
        e.Values.Add("VenueId", Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString()));
        e.Values.Add("CategoryId", Int32.Parse(CategoryNameDropDown.SelectedValue.ToString()));

    }
    protected void lvVenueUnits_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        //Check for duplication first
        DropDownList unitNameDropDown = (DropDownList)this.Find(((ListView)sender), "UnitDropDown");
        DropDownList campusNameDropDown = (DropDownList)this.Find(((ListView)sender), "CampusDropDown");


        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        List<VenueUnit> venueUnits = (from vu in db.VenueUnits
                                      where vu.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                                      && vu.IsActive == true
                                      && vu.UnitId == Int32.Parse(unitNameDropDown.SelectedValue.ToString())
                                      && vu.CampusId == Int32.Parse(campusNameDropDown.SelectedValue.ToString())
                                      select vu).ToList<VenueUnit>();

        if (venueUnits.Count > 0)
        {
            CustomValidator cv = (CustomValidator)this.Find(((ListView)sender), "DuplicateUnitValidator");
            cv.IsValid = false;
            e.Cancel = true;
            return;
        }

        //Add Rest of the values
        string user = User.Identity.Name;
        e.Values.Add("isActive", true);
        e.Values.Add("DateCreated", DateTime.Now);
        e.Values.Add("CreatedBy", user);
        e.Values.Add("DateUpdated", DateTime.Now);
        e.Values.Add("UpdatedBy", user);
        e.Values.Add("VenueId", Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString()));
        e.Values.Add("UnitId", Int32.Parse(unitNameDropDown.SelectedValue.ToString()));
        e.Values.Add("CampusId", Int32.Parse(campusNameDropDown.SelectedValue.ToString()));

    }
    protected void ldsVenueUnits_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from vu in db.VenueUnits
                    join u in db.Units on vu.UnitId equals u.UnitId
                    where vu.VenueId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                    && vu.IsActive == true
                    && u.IsActive == true
                    orderby u.UnitCode
                    select vu;

        e.Result = query;
    }
    protected void lvVenueContacts_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        string user = User.Identity.Name;

        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        Contact c = new Contact();
        c.FirstName = e.Values["FirstName"].ToString();
        c.LastName = e.Values["LastName"].ToString();
        c.Title = e.Values["Title"].ToString();
        c.JobTitle = e.Values["JobTitle"].ToString();
        c.EmailAddress = e.Values["EmailAddress"].ToString();
        c.IsActive = true;
        c.IsAgency = (bool)e.Values["IsAgency"];
        c.IsEducator = (bool)e.Values["IsEducator"];
        c.EducatorCurrentRate = Int32.Parse(e.Values["EducatorCurrentRate"].ToString());
        c.CreatedBy = user;
        c.DateCreated = DateTime.Now;
        c.DateUpdated = DateTime.Now;
        c.UpdatedBy = user;

        //DropDown Educator Type
        DropDownList educatorType = (DropDownList)this.Find(this.lvVenueContacts, "EducatorTypeDropDown");
        c.EducatorTypeId = Int32.Parse(educatorType.SelectedValue.ToString());

        //DropDown Division
        DropDownList division = (DropDownList)this.Find(this.lvVenueContacts, "DivisionDropDown");
        c.DivisionId = Int32.Parse(division.SelectedValue.ToString());

        // Create Contact Address
        ContactAddress ca = new ContactAddress();
        ca.IsActive = true;
        ca.IsCurrent = true;
        ca.IsPrimary = true;
        ca.CreatedBy = user;
        ca.DateCreated = DateTime.Now;
        ca.DateUpdated = DateTime.Now;
        ca.UpdatedBy = user;

        //Address
        Address a = new Address();
        a.Address1 = e.Values["Address1"].ToString();
        a.Address2 = e.Values["Address2"].ToString();
        a.City = e.Values["City"].ToString();
        DropDownList countryDropDown = (DropDownList)this.Find(this.lvVenueContacts, "Countries");
        a.CountryId = Int32.Parse(countryDropDown.SelectedValue.ToString());
        a.CreatedBy = user;
        a.DateCreated = DateTime.Now;
        a.DateUpdated = DateTime.Now;
        a.IsActive = true;
        a.IsPostal = true;
        a.Latitude = 0;
        a.Longitude = 0;
        a.PostCode = e.Values["PostCode"].ToString();

        DropDownList stateDropDown = (DropDownList)this.Find(this.lvVenueContacts, "States");
        a.StateId = Int32.Parse(stateDropDown.SelectedValue.ToString());
        a.Street = e.Values["Street"].ToString();
        a.UpdatedBy = user;

        db.Addresses.InsertOnSubmit(a);
        db.SubmitChanges();


        //Get Address Id
        ca.AddressId = a.AddressId;

        //Venue Contact
        VenueContact vc = new VenueContact();
        vc.VenueId = Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString());
        vc.IsActive = true;
        vc.IsPrimary = true;
        vc.CreatedBy = user;
        vc.DateCreated = DateTime.Now;
        vc.DateUpdated = DateTime.Now;
        vc.UpdatedBy = user;

        //Add to contactAddress and venue Contact
        c.ContactAddresses.Add(ca);
        c.VenueContacts.Add(vc);

        db.Contacts.InsertOnSubmit(c);
        db.SubmitChanges();

        int newAddressId = c.ContactId;
        e.Cancel = true;

        lvVenueContacts.DataBind();

    }
    protected void lvContactContactNumbers_ItemInserting(object sender, ListViewInsertEventArgs e)
    {

        string user = User.Identity.Name;

        ListView lvContactNumbers = (ListView)sender;

        HiddenField h = (HiddenField)e.Item.Parent.FindControl("contactNumbersContactId");
        

        Array ccn1 = lvContactNumbers.Items.ToArray();

        ContactContactNumber ccn = new ContactContactNumber();
        ccn.ContactId = Int32.Parse(h.Value.ToString());
        ccn.IsActive = true;
        ccn.CreatedBy = user;
        ccn.DateCreated = DateTime.Now;
        ccn.DateUpdated = DateTime.Now;
        ccn.UpdatedBy = user;

        ContactNumber c = new ContactNumber();
        //DropDown Contact Number Type
        DropDownList contactNumberType = (DropDownList)this.Find(e.Item, "ContactTypeDropDown");
        c.ContactNumberTypeId = Int32.Parse(contactNumberType.SelectedValue.ToString());
        
        TextBox t =(TextBox) this.Find(e.Item, "ContactNumberTextBox");

        //use this to vaidate the rewuired field contactnumbervalue in child
        //list view lv  ContactContactNumbers
        if (t.Text == "")
        {
            CustomValidator cv = (CustomValidator)this.Find(e.Item, "ContactNumberValidator");
            cv.IsValid = false;
            e.Cancel = true;
            return;
        }

        c.ContactNumberValue = t.Text;
       
        c.ContactContactNumbers.Add(ccn);

        List<ContactNumber> ls = (List<ContactNumber>)this.Session["ContactNumbersList"];
        if (ls == null)
            ls = new List<ContactNumber>();
        ls.Add(c);

        this.Session.Remove("ContactNumbersList");
        this.Session.Add("ContactNumbersList",ls);

        lvContactNumbers.DataSource = ls;
        lvContactNumbers.DataBind();
        e.Cancel = true;

        //string user = User.Identity.Name;

        //ListView lvContactNumbers = (ListView)sender;

        //HiddenField h = (HiddenField)e.Item.Parent.FindControl("contactNumbersContactId");

        //PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        //ContactContactNumber ccn = new ContactContactNumber();
        //ccn.ContactId = Int32.Parse(h.Value.ToString());
        //ccn.IsActive = true;
        //ccn.CreatedBy = user;
        //ccn.DateCreated = DateTime.Now;
        //ccn.DateUpdated = DateTime.Now;
        //ccn.UpdatedBy = user;

        //ContactNumber c = new ContactNumber();
        ////DropDown Contact Number Type
        //DropDownList contactNumberType = (DropDownList)this.Find(e.Item, "ContactTypeDropDown");
        //c.ContactNumberTypeId = Int32.Parse(contactNumberType.SelectedValue.ToString());

        ////use this to vaidate the rewuired field contactnumbervalue in child
        ////list view lv  ContactContactNumbers
        //if (e.Values["ContactNumberValue"] == null)
        //{
        //    CustomValidator cv = (CustomValidator)this.Find(e.Item, "ContactNumberValidator");
        //    cv.IsValid = false;
        //    e.Cancel = true;
        //    return;
        //}

        //c.ContactNumberValue = e.Values["ContactNumberValue"].ToString();

        //c.ContactContactNumbers.Add(ccn);
        //db.ContactNumbers.InsertOnSubmit(c);
        //db.SubmitChanges();

        //lvContactNumbers.DataBind();

        //e.Cancel = true;
    }

    /// <summary>
    /// Hidden field is used to save the id of the parent listview. When the Parent listview 
    /// Venue Contacts is data binded than the contactid is stored in the child contact numbers list view.
    /// ldsContactContactNumbers is used to select the appropriate contact numbers using
    /// WhereParameters
    ///      asp:ControlParameter Name="ContactId" Type="Int32" ControlID="ContactIdHiddenField"
    ///       PropertyName="Value" 
    /// WhereParameters
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lvVenueContacts_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        ListView nestedListView = ((ListView)e.Item.FindControl("lvContactContactNumbers"));

        HiddenField parentField = (HiddenField)e.Item.FindControl("ContactIdHiddenField");

        //Do this as the following code may throw error
        try
        {
            HiddenField h = (HiddenField)nestedListView.FindControl("contactNumbersContactId");
            h.Value = parentField.Value;
        }
        catch
        {
        }
    }
    protected void lvVenueContacts_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        string user = User.Identity.Name;

        ListViewItem lw = lvVenueContacts.Items[e.ItemIndex];
        HiddenField h = (HiddenField)lw.FindControl("ContactIdHiddenField");

        e.NewValues.Remove("EducatorTypeId");
        DropDownList educatorTypeDropDown = (DropDownList)lw.FindControl("EducatorTypeDropDown");
        e.NewValues.Add("EducatorTypeId", Int32.Parse(educatorTypeDropDown.SelectedValue.ToString()));

        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        Address add = (from a in db.Addresses
                       join ca in db.ContactAddresses on a.AddressId equals ca.AddressId
                       where ca.ContactId == Int32.Parse(h.Value.ToString())
                       && ca.IsPrimary == true
                       select a).ToList<Address>().First<Address>();

        //Address
        TextBox address1TextBox = (TextBox)lw.FindControl("Address1TextBox");
        add.Address1 = address1TextBox.Text;
        TextBox address2TextBox = (TextBox)lw.FindControl("Address2TextBox");
        add.Address2 = address2TextBox.Text;
        TextBox cityTextBox = (TextBox)lw.FindControl("CityTextBox");
        add.City = cityTextBox.Text;
        TextBox streetTextBox = (TextBox)lw.FindControl("StreetTextBox");
        add.Street = streetTextBox.Text;
        DropDownList countryDropDown = (DropDownList)lw.FindControl("Countries");
        add.CountryId = Int32.Parse(countryDropDown.SelectedValue.ToString());
        add.DateUpdated = DateTime.Now;
        add.IsPostal = true;
        TextBox postCodeTextBox = (TextBox)lw.FindControl("PostCodeTextBox");
        add.PostCode = postCodeTextBox.Text;
        //////ToDo: StateID
        DropDownList stateDropDown = (DropDownList)lw.FindControl("States");
        add.StateId = Int32.Parse(stateDropDown.SelectedValue.ToString());
        add.UpdatedBy = user;

        db.SubmitChanges();
    }
    protected void gvNotes_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        e.NewValues.Add("DateUpdated", DateTime.Now);
        e.NewValues.Add("UpdatedBy", User.Identity.Name);
    }
    protected void btnSaveNote_Click(object sender, EventArgs e)
    {
        if (this.gvVenues.Rows.Count > 0)
        {
            PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();
            Note n = new Note();

            string user = User.Identity.Name;

            n.EntityId = Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString());
            n.NoteText = this.txtAddNewNote.Text;
            n.NoteTypeId = 2;
            n.IsActive = true;
            n.CreatedBy = user;
            n.DateCreated = DateTime.Now;
            n.UpdatedBy = user;
            n.DateUpdated = DateTime.Now;
            db.Notes.InsertOnSubmit(n);
            db.SubmitChanges();
            gvNotes.DataBind();

            //Update the panel as grid view doesnot refresh on addition.
            UpdatePnlNotes.Update();
        }
    }
    protected void ldsComments_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        PlacementManagerLinqDataContext db = new PlacementManagerLinqDataContext();

        var query = from n in db.Notes
                    where n.EntityId == Int32.Parse(this.gvVenues.SelectedDataKey.Value.ToString())
                    && n.IsActive == true
                    orderby n.DateUpdated
                    select n;
        e.Result = query;
    }
    protected void lvContactContactNumbers_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        ListView lvContactNumbers = (ListView)sender;

        List<ContactNumber> ls = (List<ContactNumber>)this.Session["ContactNumbersList"];
        if (ls == null)
            ls = new List<ContactNumber>();

        Label t = (Label)this.Find(lvContactNumbers.Items[e.ItemIndex], "ContactNumberValueLabel");
        foreach (ContactNumber c in ls)
        {
            if (c.ContactNumberValue == t.Text)
            {
                ls.Remove(c);
                break;
            }
        }

        this.Session.Remove("ContactNumbersList");
        this.Session.Add("ContactNumbersList", ls);

        lvContactNumbers.DataSource = ls;
        lvContactNumbers.DataBind();
        e.Cancel = true;
    }
}
